package com.znyj.cloud.chain.dispatch;

import com.znyj.cloud.chain.dispatch.annotation.Executor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by gaoliwei on 15-2-9.
 */
public abstract class AbstractAnnotationHandlerMapping implements ApplicationContextAware {

    protected ApplicationContext applicationContext;

    private List<HandlerExecution> handlerExecutionChain = new ArrayList<>();
    private List<Object> executors = new ArrayList<>();

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        initExecutors();
    }

    /**
     * 为一个类定义处理链
     *
     * @param executor
     */
    protected abstract List<HandlerExecution> resolveExecutionChain(Object executor);

    /**
     * 得到所有的executor
     */
    protected void initExecutors() {
//        String[] beanNames = applicationContext.getBeanNamesForAnnotation(Executor.class);
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Executor.class);
//        for (String beanName : beanNames) {
//            executors.addAll(applicationContext.getBean(beanName));
//        }
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            executors.add(entry.getValue());
        }

        for (Object executor : executors) {
            handlerExecutionChain.addAll(resolveExecutionChain(executor));
        }
    }

    protected Object execute(String patchTarget, Object... args) {
        for (HandlerExecution execution : handlerExecutionChain) {
            if (execution.patch(patchTarget)) {
                return execution.execute(args);
            }
        }
        return null;
    }

}
